﻿using System;
using System.Collections.Generic;
using System.Linq;
using Sirenix.OdinInspector;
# if UNITY_EDITOR
using Sirenix.Utilities.Editor;
# endif
using UnityEngine;

namespace Gp.AI {
    [Serializable]
    public class AttackTargetWeight {
        [LabelText("目标权重")]
        [SerializeField]
        [OnValueChanged("OnListChanged")]
        [ValueDropdown("ValueDropDown", DrawDropdownForListElements = false)]
        [ListDrawerSettings(DraggableItems = false, OnBeginListElementGUI = "BeginDraw",
            OnEndListElementGUI = "EndDraw")]
        [GUIColor(1.5f, 1.5f, 1.5f)]
        private List<WeightInfo> list = new();


        public WeightInfo GetWeight(AtkWeight type) {
            return new WeightInfo(type, list.Where(x => x.weight == type).Sum(x => x.num));
        }


        #region Editor

# if UNITY_EDITOR
        [Button("恢复默认")]
        public void Reset() {
            list = new List<WeightInfo>();
            foreach (AtkWeight w in Enum.GetValues(typeof(AtkWeight))) {
                list.Add(new WeightInfo(w, w.DefaultValue()));
            }
        }

        [Button("排序")]
        private void ReSort() {
            list.Sort((a1, a2) => a1.weight - a2.weight);
        }

        private IEnumerable<ValueDropdownItem<WeightInfo>> ValueDropDown() {
            List<ValueDropdownItem<WeightInfo>> res = new();
            var set = new HashSet<AtkWeight>(list.Select(x => x.weight));
            foreach (AtkWeight w in Enum.GetValues(typeof(AtkWeight))) {
                if (set.Contains(w)) continue;
                res.Add(new ValueDropdownItem<WeightInfo>(w.Label(), new WeightInfo(w, w.DefaultValue())));
            }

            return res;
        }


        private void OnListChanged() {
            ReSort();
        }


        private void BeginDraw(int index) {
            SirenixEditorGUI.BeginBox(index.ToString());
        }


        private void EndDraw(int index) {
            var sum = list.Sum(x => x.num);
            var num = list[index].num;
            float percent = sum == 0 ? 0 : num / (float) sum;
            string text = percent.ToString("P1");
            SirenixEditorFields.ProgressBarField($"占比 : {text}", num, 0, sum);
            SirenixEditorGUI.EndBox();
        }


#endif

        #endregion
    }
}